<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/8/25
 * Time: 17:26
 */

namespace Home\Logic;


use Admin\Logic\MoneyLogLogic;
use Common\Utils\Constants;
use Home\Model\Page;
use Think\Exception;
use Think\Log;

class GoodsLogic
{
    /**
     * 获取已经上架未删除的商品
     * @param $map
     * @param int $pagenum
     * @param int $pagesize
     * @return mixed
     */
    public function getGoodsList($map,$pagenum=1,$pagesize=20){
        $startno = ($pagenum - 1) * $pagesize;
        $limit = $startno . ',' . $pagesize;//每页的数据数和内容$limit
        $map['is_delete'] = 0;
        $map['is_shelves'] = 1;
        $roomList = D('Goods')->field('t_goods.*')
            ->where($map)
            ->order('id desc')->limit($limit)
            ->select();
//        foreach ($roomList as $key => $value){
//            $roomList[$key]['game_start_time'] = date('m月d日 H:s',$value['game_start_time']);
//            $roomList[$key]['model_name'] = $value['model'] == 0 ?'1v1' : ($value['model'] == 1?'3v3':'5v5');
//        }
        $data['list'] = $roomList;
        $count = D('Goods')->where($map)->count();
        $page = new Page($pagenum, $count, $pagesize);
        $page = (array)$page;//转换为数组
        $data['page'] = $page;
        return $data;
    }

    /**
     * 用户兑换
     * @param $goods_id int 商品id
     * @param $user_id int 用户id
     * @return int 0失败 1成功 2钻石不足 3该商品不存在
     */
    public function award($goods_id,$user_id){
        $goods = D('Goods')->where(array('id'=>$goods_id))->find();
        if(!$goods){
            return 3;
        }
        $integral = D('User')->where(array('id'=>$user_id))->getField('integral');
        $money = $goods['money'] * 10 + $goods['poundage'];
        if($integral < $money){
            return 2;
        }
        $model = M();
        $model->startTrans();
        try {
            //扣除用户钻石
            $this->decIntegral($integral,$goods,$money,$user_id,$model);
            $orderLogic = new OrderLogic();
            $orderLogic->addOrder($goods,$user_id,$model);
            $model->commit();
            return 1;
        }catch (Exception $e){
            Log::write($e->getMessage());
            $model->rollback();
            return 0;
        }
    }

    /**
     * 扣除用户钻石
     * @param $integral int 用户当前钻石
     * @param $goods array 购买充值卡
     * @param $money int 所需金额
     * @param $user_id int 用户id
     * @param $model object
     */
    private function decIntegral($integral,$goods,$money,$user_id,$model){
        $remark = '使用钻石兑换' . $goods['title'];
        $moneyLogic = new MoneyLogLogic();
        $moneyLogic->saveMoneyLog($money,
            $integral - $money,
            Constants::MONEY_SOURCE_EXCHANGE,
            Constants::PUT_TYPE_OUT,
            $remark, $user_id, Constants::MONEY_TYPE_INTEGRAL, $model);
        $model->table('t_user')->where(array('id'=>$user_id))->setDec('integral',$money);
    }
}